/*
 * cStateManager.cpp
 *
 *  Created on: 11.2.2009
 *      Author: jari.ravantti
 */

#include "CStateManager.h"
#include "CStateBase.h"
#include <iostream>

using namespace std;


void CStateManager::Init() {
	#ifdef DEBUG
	CLogger::Instance()->log(LOG_LEVEL_NOTICE,"StateManager init called!");
	#endif

		//Set up window
		if (!m_Window.createWindow(WIDTH, HEIGHT, 32, FULLSCREEN, TITLE)) {
			#ifdef DEBUG
	CLogger::Instance()->log(LOG_LEVEL_ERROR,"StateManager init failed!");
	#endif
			Cleanup();
			m_running = false;
		}
		//set gl bg-color and finish init
		glClearColor(0.0, 0.0, 0.0, 1.0);
		m_running = true;
}

void CStateManager::Cleanup() {
	//empties state stack and calls sdl_quit()
	#ifdef DEBUG
	CLogger::Instance()->log(LOG_LEVEL_NOTICE,"StateManager cleanup called!");
	#endif
	while (!states.empty()) {
		states.back()->Cleanup();
		states.pop_back();
	}
	SDL_Quit();

}

void CStateManager::Pause(){
	states.back()->Pause();
}

void CStateManager::Resume(){
	states.back()->Resume();
}

void CStateManager::HandleEvents() {
	states.back()->HandleEvents(this);
}

void CStateManager::Update() {
	states.back()->Update(this);
}

void CStateManager::Draw() {
	states.back()->Draw(this);
}

void CStateManager::ChangeState(CStateBase* state) {
	// cleanup the current state
		if ( !states.empty() ) {
			states.back()->Cleanup();
			states.pop_back();
		}

		// store and init the new state
		states.push_back(state);
		states.back()->Init();

}

void CStateManager::PushState(CStateBase* state) {
	if (!states.empty()) {
		states.back()->Cleanup();
	}
	//Push state to stack top and init
	states.push_back(state);
	states.back()->Init();

}

void CStateManager::PopState() {
	if (!states.empty()) {
		states.back()->Cleanup();
		states.pop_back();
	}
	//pop top state from stack and set the next to top and call resume function from it
	if (!states.empty()) {
		states.back()->Resume();
	}
}


